package com.boot.auth.support.core;

import cn.hutool.core.bean.BeanUtil;
import com.boot.framework.token.utils.AuthUtils;
import com.boot.system.dto.SysMenuDTO;
import com.boot.system.fegin.SysMenuClient;
import com.boot.system.fegin.SysUserClient;
import com.google.common.collect.ArrayListMultimap;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yangfan
 * @date 2023/12/28
 * @Description
 */
@RequiredArgsConstructor
@Component
public class PermissionService {

    private final SysMenuClient sysMenuClient;

    public List<SysMenuDTO> buildRouter() {
        if (AuthUtils.isAdmin()) {
            Map<String, Object> map = new HashMap<>();
            List<SysMenuDTO> sysMenuDTOS = sysMenuClient.selectList(map).getData();
            return buildRouterTree(sysMenuDTOS);
        } else {
            List<String> roles = new ArrayList<>(AuthUtils.getRoles());
            List<SysMenuDTO> sysMenuDTOS = sysMenuClient.selectListByRoleIds(new SysMenuDTO(), roles).getData();
            return buildRouterTree(sysMenuDTOS);

        }
    }

    private List<SysMenuDTO> buildRouterTree(List<SysMenuDTO> sysMenuDTOS) {
        //获取一级菜单
        List<SysMenuDTO> rootMenu = new ArrayList<>();
        ArrayListMultimap<String, SysMenuDTO> menuMap = ArrayListMultimap.create();
        for (SysMenuDTO sysMenu : sysMenuDTOS) {
            if (sysMenu.getParentId().equals("0")) {
                rootMenu.add(sysMenu);
            } else {
                //其余节点放进map
                menuMap.put(sysMenu.getParentId(), sysMenu);
            }
        }
        //递归封装树形结构
        for (SysMenuDTO menu : rootMenu) {
            List<SysMenuDTO> sysMenuDTOList = findChildren(menu, menuMap);
            menu.getChildren().addAll(sysMenuDTOList);
        }
        return rootMenu;
    }

    private List<SysMenuDTO> findChildren(SysMenuDTO menu, ArrayListMultimap<String, SysMenuDTO> menuMap) {
        List<SysMenuDTO> children = menuMap.get(menu.getMenuId());
        for (SysMenuDTO temp : children) {
            List<SysMenuDTO> sysMenuDTOList = findChildren(temp, menuMap);
            temp.getChildren().addAll(sysMenuDTOList);
        }
        return children;
    }

}
